import kaa.metadata
import spl
import os, os.path
import sys
import getopt

byArtist = {}
byDirectoryGroup = {}
all = []
#start = '/home/nigel/misc/Music'
#playlists = '/home/nigel/misc/Music/playlists'
def showUsage():
	print "main.py [-e <excluded directory> ...] <Root directory> <Playlist directory>"


if __name__ == '__main__':
	optlist, args = getopt.getopt(sys.argv[1:],'e:')
	if len(args) != 2:
		showUsage()
		sys.exit(1)
	else:
		start = args[0]
		playlists = args[1]
		excludeList = []
		for tag, exdir in optlist:
			if tag == '-e':
				excludeList.append(exdir)
	# Iterate through the dirs below the start dir
	for root, dirs, files in os.walk(start):
		# Check the dir isn't excluded
		skip = False
		for ex in excludeList:
			if root.startswith(ex):
				print "skipping", root
				skip = True
				continue
		if skip:
			continue

		for f in files:
			md = kaa.metadata.parse(os.path.join(root, f))
			if md != None and md.mime == u'audio/mpeg':
				artist = md.artist
				if artist != None:
					artist = artist.title()
				else:
					artist = u"None"
				if byArtist.has_key(artist):
					byArtist[artist].append(md)
				else:
					byArtist[artist] = [md]
				all.append(md)

	for a in byArtist:
		files = [md.fileName.replace(start,'').replace('/','\\') for md in byArtist[a] ]
		pl = spl.SPL()
		pl.list = files
		pl.save(os.path.join(playlists, a+'.spl'))

	# Store all playlist
	files = [md.fileName.replace(start,'') for md in all ]
	pl = spl.SPL()
	pl.list = files
	pl.save(os.path.join(playlists, 'All Artists.spl'))
